package com.example._10Rabbitmq插件实现延迟队列.controller;

import com.example._10Rabbitmq插件实现延迟队列.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 生产者
 * 支持延迟投递机制，消息传递后并不会立即投递到目标队列中，
 * 而是存储在 mnesia(一个分布式数据系统)表中，当达到投递时间时，才投递到目标队列中
 * @author linjy on 2022/8/20
 */
@Slf4j
@RequestMapping("ttl")
@RestController
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 开始发消息基于插件的消息及延迟的时间
     */
    @GetMapping("sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message, @PathVariable Integer delayTime) {
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message,
                correlationData -> {
                    correlationData.getMessageProperties().setDelay(delayTime);
                    return correlationData;
                });
        //发送消息的时候延迟时长单位:ms
        log.info("当前时间：{},发送一条延迟{}毫秒的信息给队列 delayed.queue:{}", new Date(), delayTime, message);
    }

}
